文章目录
  1. Can we use string for switch statement?
    Yes to version 7. From JDK 7, we can use string as switch condition. Before version 6, we can not use string as switch condition.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    // java 7 only!
    switch (str.toLowerCase()) {
    case "a":
    value = 1;
    break;
    case "b":
    value = 2;
    break;
    }
  2. How to split a string with white space characters?

    1
    String[] strArray = aString.split("\\s+");
  3. What substring() method really does?
    In JDK 6, the substring() method gives a window to an array of chars which represents the existing String, but do not create a new one. To create a new string represented by a new char array, you can do add an empty string like the following:

    1
    str.substring(m, n) + ""

    This will create a new char array that represents the new string. The above approach sometimes can make your code faster, because Garbage Collector can collect the unused large string and keep only the sub string.

    In Oracle JDK 7, substring() creates a new char array, not uses the existing one.

  4. How to repeat a string?
    we can use the repeat() method of StringUtils from Apache Commons Lang package.

    1
    2
    3
    String str = "abcd";
    String repeated = StringUtils.repeat(str,3);
    //abcdabcdabcd
  5. How to convert string to date?

    1
    2
    3
    4
    String str = "Sep 17, 2013";
    Date date = new SimpleDateFormat("MMMM d, yy", Locale.ENGLISH).parse(str);
    System.out.println(date);
    //Tue Sep 17 00:00:00 EDT 2013
  6. How to count ‘#’ of occurrences of a character in a string?
    Use StringUtils from apache commons lang.

    1
    2
    int n = StringUtils.countMatches("11112222", "1");
    System.out.println(n);
  7. How to detect if a string contains only uppercase letter?
    Use java.lang.Character
    isUpperCase() and isLetter() ;

文章目录